package com.hzc.springchan.strategy.paramcheck;

import com.hzc.springchan.annotation.CParam;
import com.hzc.springchan.bean.exception.CException;
import com.hzc.springchan.bean.request.Request;
import com.hzc.springchan.config.resthelp.RequestConcurrent;
import com.hzc.springchan.enums.CParamCheck;
import com.hzc.springchan.enums.PrivError;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 参数校验策略调用环境类
 * @author chen990627
 * @date 2022/10/18
 */
@Component
public class ParamCheckContext {

    @Autowired
    private Map<String, IParamCheckStrategy> container;

    @Autowired
    private RequestConcurrent requestConcurrent;

    public void paramCheck(CParam cParam) {

        Request request = requestConcurrent.getCurrentRequest();
        for (CParamCheck cParamCheck : cParam.values()) {
            for (Map.Entry<String, IParamCheckStrategy> entry : container.entrySet()) {
                if (entry.getKey().equals(cParamCheck.getName())) {
                    if (!entry.getValue().paramCheck(request, cParam.params())) {
                        throw new CException(PrivError.CPARAM_CHECK_FAILED, true);
                    }
                }
                break;
            }
        }
    }
}
